//**********************************************************************
//系统名					优儿宝家长-安卓版
//class名					NetUtil
//主要功能					访问网络信息帮助类
//
//===================================================
//version			变更日					变更者			变更内容
//------------------------------------------------------------------------------------------
//2.2.0				2015-03-24				wcj			作成
//**********************************************************************

package com.moxigua.iotbox.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

/**
 * 访问网络信息帮助类
 * 
 * @author lixl
 */
public class NetUtil {

	private static String TAG = NetUtil.class.getName();

	/** 缓冲大小 */
	private static final int BUFFER = 10240 * 2;
	/** 超时时间：6 * 1000 */
	private static final int TIMEOUT = 1000 * 11;

	/**
	 * 创建HttpClient
	 * 
	 * @return HttpClient
	 */
	public static HttpClient getHttpClient() {
		// 创建一个 HttpClient 实例
		HttpClient httpClient = new DefaultHttpClient();
		// 创建 HttpParams 以用来设置 HTTP 参数（这一部分不是必需的）
		HttpParams httpParams = httpClient.getParams();
		// 设置连接超时和 Socket 超时，以及 Socket 缓存大小
		HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT);
		HttpConnectionParams.setSocketBufferSize(httpParams, BUFFER);
		// 设置重定向，缺省为 true
		HttpClientParams.setRedirecting(httpParams, true);
		// 协议
		httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
				HttpVersion.HTTP_1_1);
		return httpClient;
	}

	/**
	 * 通过Get方式取得访问结果
	 * 
	 * @param strUrl
	 *            访问地址URL字符串
	 * @param parp
	 *            URL参数MAP
	 * @return String 取得访问结果
	 */
	public static String sendHttpGet(String strUrl, Map<String, Object> parp) {
		String url = strUrl;
		String queryStr = getQueryStr(parp);
		if (queryStr != null && !queryStr.equals("")) {
			url += "?" + queryStr;
		}
		return sendHttpGet(url);
	}

	/**
	 * 通过Get方式取得访问结果
	 * 
	 * @param strUrl
	 *            访问地址URL字符串
	 * @return String 取得访问结果
	 */
	public static String sendHttpGet(String strUrl) {
		String result = null;
		try {
			// 创建一个HttpGet对象
			HttpGet get = new HttpGet(strUrl);
			// 发送GET请求
			HttpResponse response = getHttpClient().execute(get);
			// 如果服务器成功地返回响应
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
				result = EntityUtils.toString(response.getEntity());
			}
		} catch (ClientProtocolException e) {
			Log.d(TAG, e.getMessage(), e);
		} catch (IOException e) {
			Log.d(TAG, e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 通过POST方式取得访问结果
	 * 
	 * @param strUrl
	 *            访问地址URL字符串
	 * @param parp
	 *            URL参数MAP
	 * @return String 取得访问结果
	 */
	public static String sendHttpPost(String strUrl, Map<String, Object> parp) {
		String result = null;
		try {
			HttpPost post = new HttpPost(strUrl);
			// 如果传递参数个数比较多的话可以对传递的参数进行封装
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for (Map.Entry<String, Object> entry : parp.entrySet()) {
				String value = (String) entry.getValue();
				params.add(new BasicNameValuePair(entry.getKey(),
						value == null ? "" : value));
			}
			// 设置请求参数
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			// 发送POST请求
			HttpResponse response = getHttpClient().execute(post);
			// 如果服务器成功地返回响应
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
				result = EntityUtils.toString(response.getEntity());
			}
		} catch (ClientProtocolException e) {
			Log.d(TAG, e.getMessage(), e);
		} catch (IOException e) {
			Log.d(TAG, e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 文件下载,边下边写
	 * 
	 * @param strUrl
	 *            访问地址URL字符串
	 * @param path
	 *            存储路径
	 * @param androidHandler
	 *            Handler对象
	 * @return File 存储文件
	 */
	public static File downloadFile(String strUrl, String path,
			Handler androidHandler) {
		File file = null;
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			URI uri = new URL(strUrl).toURI();
			file = new File(path);
			int responseCode = 0;
			InputStream is;
			HttpClient httpClient = getHttpClient();
			HttpResponse httpResponse = null;
			HttpGet httpGet = new HttpGet(uri);

			httpResponse = httpClient.execute(httpGet);

			responseCode = httpResponse.getStatusLine().getStatusCode();

			if (HttpStatus.SC_OK == responseCode) {
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();

				in = new BufferedInputStream(is, BUFFER);
				if (!file.exists()) {
					File parentDir = file.getParentFile();
					if (parentDir != null && !parentDir.exists()) {
						parentDir.mkdirs();
					}
					file.createNewFile();
				}
				out = new BufferedOutputStream(
						new FileOutputStream(file, false), BUFFER);

				byte buf[] = new byte[BUFFER];
				int size = -1;
				if (null == androidHandler) {
					while ((size = in.read(buf)) != -1) {
						out.write(buf, 0, size);
					}
				} else {
					long length = httpEntity.getContentLength();
					if (-1 == length) {
						androidHandler.sendMessage(androidHandler
								.obtainMessage(0, Long.valueOf(-1)));
					} else {
						androidHandler.sendMessage(androidHandler
								.obtainMessage(0, Long.valueOf(length)));
					}
					long count = 0;
					while (-1 != (size = in.read(buf))) {
						out.write(buf, 0, size);
						count += size;
						androidHandler.sendMessage(androidHandler
								.obtainMessage(0, count));
					}
				}
				out.flush();
			}
		} catch (URISyntaxException e) {
			Log.d(TAG, e.getMessage(), e);
		} catch (ClientProtocolException e) {
			Log.d(TAG, e.getMessage(), e);
		} catch (IOException e) {
			Log.d(TAG, e.getMessage(), e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (Exception e) {
			}
		}
		return file;
	}

	/**
	 * 根据MAP信息，取得GET方式的查询条件
	 * 
	 * @param paramMap
	 *            查询条件MAP
	 * @return String 查询条件字符串
	 */
	public static String getQueryStr(Map<String, Object> paramMap) {
		String qStr = null;
		if (paramMap != null && !paramMap.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			Set<String> keySet = paramMap.keySet();
			for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
				String key = it.next();
				Object value = paramMap.get(key);
				if (value != null) {
					sb.append(key);
					sb.append("=");
					sb.append(value);
					sb.append("&");
				}
			}
			qStr = sb.toString();
			if (qStr.endsWith("&")) {
				qStr = qStr.substring(0, qStr.length() - 1);
			}
		}

		return qStr;
	}

	/**
	 * 安装APK
	 * 
	 * @param context
	 *            上下文内容对象
	 * @param fileName
	 *            文件名
	 */
	public static void installApk(Context context, String fileName) {
		if (TextUtils.isEmpty(fileName)) {
			return;
		}

		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction("android.intent.action.VIEW");
		intent.setDataAndType(Uri.fromFile(new File(fileName)),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}

	/** 网络状态-无网络 */
	public final static int NETWORK_STATE_NONE = 0;
	/** 网络状态-Wi-Fi */
	public final static int NETWORK_STATE_WIFI = 1;
	/** 网络状态-3G,GPRS */
	public final static int NETWORK_STATE_MOBILE = 2;

	/**
	 * 获取当前网络状态
	 * 
	 * @param context
	 *            上下文内容对象
	 * @return int 网络状态，无网络【0】，Wi-Fi【1】，3G,GPRS【2】
	 */
	public static int getNetworkState(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		// Wifi网络判断
		State state1 = connManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if (state1 == State.CONNECTED || state1 == State.CONNECTING) {
			return NETWORK_STATE_WIFI;
		}
		NetworkInfo networkInfo = connManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (networkInfo == null) {
			return NETWORK_STATE_NONE;
		}
		// 手机网络判断
		State state = networkInfo.getState();
		if (state == State.CONNECTED || state == State.CONNECTING) {
			return NETWORK_STATE_MOBILE;
		}

		return NETWORK_STATE_NONE;
	}

}